﻿using System;
using System.Windows.Forms;
using QuanLyThuPhiTaiLieu.Biz;
using QuanLyThuPhiTaiLieu.Common;
using QuanLyThuPhiTaiLieu.Entity;
using System.IO;
using System.Collections.Generic;
using Telerik.WinControls.UI;
using Telerik.WinControls.Data;
using System.ComponentModel;

namespace QuanLyThuPhiTaiLieu.Forms
{
    public partial class NewBangKeKhaiPhiSuDung : Form
    {
        private List<PhieuBanGiaoTaiLieuChiTiet> listChiTiet;
        public List<PhieuBanGiaoTaiLieuChiTiet> ListChiTiet
        {
            get
            {
                if (listChiTiet == null)
                {
                    return new List<PhieuBanGiaoTaiLieuChiTiet>();
                }
                else
                {
                    return listChiTiet;
                }
            }
            set
            {
                listChiTiet = value;
            }
        }

        private int id;

        private int attachId;

        public NewBangKeKhaiPhiSuDung()
        {
            InitializeComponent();

            GridViewSummaryItem total = new GridViewSummaryItem("ThanhTien", "Tổng tiền = {0: #,#}", GridAggregateFunction.Sum);

            GridViewSummaryRowItem summaryRowItem = new GridViewSummaryRowItem(new GridViewSummaryItem[] { total });
            radGridView1.SummaryRowsTop.Add(summaryRowItem);

            textNgay.Text = DateTime.Now.Day.ToString();
            textThang.Text = DateTime.Now.Month.ToString();
            textNam.Text = DateTime.Now.Year.ToString();

            buttonUploadFile.Visible = false;
        }

        public NewBangKeKhaiPhiSuDung(int id)
        {
            InitializeComponent();

            GridViewSummaryItem total = new GridViewSummaryItem("ThanhTien", "Tổng tiền = {0: #,#}", GridAggregateFunction.Sum);

            GridViewSummaryRowItem summaryRowItem = new GridViewSummaryRowItem(new GridViewSummaryItem[] { total });
            radGridView1.SummaryRowsTop.Add(summaryRowItem);

            this.id = id;
            buttonUploadFile.Visible = false;

            if (id > 0)
            {
                var biz = new PhieuBanGiaoTaiLieuBiz();
                var item = biz.LoadItem(id);

                textNguoiNhan.Text = item.NguoiNhan;
                textChucDanh.Text = item.ChucDanh;
                textDonVi.Text = item.DonVi;
                textDiaChi.Text = item.DiaChi;
                textThongTinChiTiet.Text = item.ThongTinChiTiet;
                textHinhThucThanhToan.Text = item.HinhThucThanhToan;
                textNguoiGiao.Text = item.NguoiGiao;
                textTpLtdc.Text = item.Tpltdc;
                textGiamDoc.Text = item.GiamDoc;
                textNgay.Text = item.NgayThang.Day.ToString();
                textThang.Text = item.NgayThang.Month.ToString();
                textNam.Text = item.NgayThang.Year.ToString();
                textDienThoai.Text = item.DienThoai;
                textSoPhieu.Text = item.SoPhieu;

                buttonUploadFile.Visible = true;
            }

            textNguoiNhan.Focus();
        }

        private void SaveItem(object sender, EventArgs e)
        {
            if (Validate())
            {
                string message;

                var biz = new PhieuBanGiaoTaiLieuBiz();

                var item = new PhieuBanGiaoTaiLieu
                {                   
                    NguoiNhan = textNguoiNhan.Text,
                    ChucDanh = textChucDanh.Text,
                    DonVi = textDonVi.Text,
                    DiaChi = textDiaChi.Text,
                    ThongTinChiTiet = textThongTinChiTiet.Text,
                    HinhThucThanhToan = textHinhThucThanhToan.Text,
                    NguoiGiao = textNguoiGiao.Text,
                    DienThoai = textDienThoai.Text,
                    Tpltdc = textTpLtdc.Text,
                    GiamDoc = textGiamDoc.Text,
                    NgayThang = new DateTime(int.Parse(textNam.Text), int.Parse(textThang.Text), int.Parse(textNgay.Text)),
                    Nam = int.Parse(textNam.Text),
                    SoPhieu = textSoPhieu.Text
                };                

                if (id > 0)
                {
                    item.Id = id;

                    if (attachId > 0)
                    {
                        item.AttachmentId = attachId;
                    }

                    biz.UpdateItem(item);
                    message = Constants.Messages.UpdateCompleted;
                }
                else
                {
                    biz.SaveItem(item);
                    message = Constants.Messages.InsertCompleted;
                }

                SaveDetail(item.Id);

                MessageBox.Show(message);
                if (id > 0)
                {
                    //Utilities.CloseForm(this, new ViewBangKeKhaiPhiSuDungTaiLieu());
                }
                else
                {
                    Utilities.CloseForm(this, new ViewBangKeKhaiPhiSuDungTaiLieu());
                }
            }
        }
        
        private void Cancel(object sender, EventArgs e)
        {
            Utilities.CloseForm(this, new ViewBangKeKhaiPhiSuDungTaiLieu());
        }

        private new bool Validate()
        {
            bool hasError = true;
            bool isFocused = false;
            errorProvider.Clear();

            if (string.IsNullOrEmpty(textNguoiNhan.Text))
            {
                errorProvider.SetError(textNguoiNhan, Constants.Messages.RequireMessage);
                hasError = false;

                textNguoiNhan.Focus();
                isFocused = true;
            }

            if (string.IsNullOrEmpty(textChucDanh.Text))
            {
                errorProvider.SetError(textChucDanh, Constants.Messages.RequireMessage);
                hasError = false;

                if (!isFocused)
                {
                    textChucDanh.Focus();
                }
                isFocused = true;
            }

            if (string.IsNullOrEmpty(textDonVi.Text))
            {
                errorProvider.SetError(textDonVi, Constants.Messages.RequireMessage);
                hasError = false;
                if (!isFocused)
                {
                    textDonVi.Focus();
                }
            }

            return hasError;
        }

        private void SetPreferences()
        {
            radGridView1.MasterTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
            radGridView1.EnableHotTracking = true;

            this.radGridView1.MasterTemplate.EnableGrouping = true;
            this.radGridView1.MasterTemplate.AllowDragToGroup = false;
            this.radGridView1.MasterTemplate.AutoExpandGroups = true;
            this.radGridView1.ShowGroupPanel = false;
            this.radGridView1.AllowAddNewRow = false;

            GroupDescriptor descriptor2 = new GroupDescriptor();
            descriptor2.GroupNames.Add("GroupValue", ListSortDirection.Ascending);            
            this.radGridView1.GroupDescriptors.Add(descriptor2);            
        }

        private void FormLoad(object sender, EventArgs e)
        {
            var parent = MdiParent as MDI;
            if (parent != null)
            {
                //Utilities.ResetBackColor(parent.TopMenu, Constants.MenuIndex.TaiLieuVanBanPhapLy);
                parent.Status.Text = Constants.FormStatus.PhieuBanGiao;
            }            

            if (id > 0)
            {
                SetPreferences();
                RefreshDetailView(id);
            }
        }

        private void NewDetail(object sender, EventArgs e)
        {
            var form = new NewBangKeKhaiPhiSuDungChiTiet();            
            form.ShowDialog(this);
            RefreshDetailView(0);            
        }

        public void RefreshDetailView(int id)
        {   
            radGridView1.DataSource = null;

            var biz = new PhieuBanGiaoTaiLieuChiTietBiz();

            if (id > 0)
            {
                listChiTiet = biz.LoadItemsByParentId(id);
            }
            
            radGridView1.DataSource = listChiTiet;
            radGridView1.Refresh();
        }

        private void SaveDetail(int id)
        {
            var data = (List<PhieuBanGiaoTaiLieuChiTiet>)radGridView1.DataSource;
            if (data != null && data.Count > 0)
            {
                var biz = new PhieuBanGiaoTaiLieuChiTietBiz();
                foreach (var item in data)
                {
                    item.PhieuBanGiao = id;
                    biz.UpdateItem(item);
                }                
            }
        }

        private void EditDetail(object sender, EventArgs e)
        {
            var dataRowInfo = radGridView1.CurrentRow as GridViewDataRowInfo;
            if (dataRowInfo != null)
            {
                var id = (int)dataRowInfo.Cells[8].Value;

                var form = new NewBangKeKhaiPhiSuDungChiTiet(id);
                form.ShowDialog(this);
                RefreshDetailView(this.id);   
            }
        }

        private void DeleteDetail(object sender, EventArgs e)
        {
            if (MessageBox.Show(Constants.Messages.DeleteConfirm, Constants.Messages.DeleteCaption, MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                var items = new List<PhieuBanGiaoTaiLieuChiTiet>();
                List<int> listItems = new List<int>();

                int count = radGridView1.Rows.Count;
                int i = 0;
                while (i < count)
                {
                    var row = radGridView1.Rows[i];
                    if (row.Cells[0].Value != null && (bool)row.Cells[0].Value)
                    {
                        items.Add(row.DataBoundItem as PhieuBanGiaoTaiLieuChiTiet);
                        radGridView1.Rows.RemoveAt(i);                        
                        count--;
                    }
                    else
                    {
                        i++;
                    }
                }

                radGridView1.Refresh();

                var biz = new PhieuBanGiaoTaiLieuChiTietBiz();
                biz.RemoveItem(items);
                if (this.id > 0)
                {
                    RefreshDetailView(this.id);
                }                
            }
        }

        private void UploadFileData(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.CheckFileExists = true;
            openFileDialog.AddExtension = true;
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var biz = new AttachmentBiz();
                var attachment = new Attachment();
                

                var stream = openFileDialog.OpenFile();
                var length = stream.Length;                
                attachment.Content = new byte[length];
                stream.Read(attachment.Content, 0, (int)length);
                attachment.FileName = Path.GetFileName(openFileDialog.FileName);

                biz.SaveItem(attachment);
                attachId = attachment.Id;
                labelFileUpdated.Text = attachment.FileName;
            }
        }
    }
}
